<?php if (! defined('APPPATH')) die('No direct script access allowed');
/**
 * RENARTI IK
 * An open source application development framework for PHP 5.2.0 or newer
 *
 * @package		RtiFramework
 * @author		Nauris Dambis <nauris.dambis@renarti.com>
 * @copyright	Copyright (c) 2012, RENARTI IK.
 * @license		http://renarti.com/#license
 * @link		http://renarti.com
 * @since		Version 1.0
 */

class RtiApplication
{
	/**
	 * Constructor
	 *
	 * Initialize the Application, route URI, run autoloads and run controller
	 *
	 * @access	public
	 * @return	void
	 */
	public function __construct()
	{		
		date_default_timezone_set(Rti::config('config')->get('DEFAULT_TIMEZONE'));	
		
		if (Rti::config('config')->get('SESSION_AUTOSTART'))
		{
			Rti::session()->start();	
		}		
		
		Rti::benchmark()->start('bm_application');
		
		$this->_route_uri();
		
		$this->_init_autoloads();
	}
	
	protected function _init_autoloads()
	{
		$autoload = Rti::config('autoloads')->items();

		Rti::loadConfig($autoload['CONFIG']);
		
		Rti::loadHelper($autoload['HELPERS']);
		
		Rti::loadCore('RtiController');		
		Rti::loadController($autoload['CONTROLLERS']);	
	}
	
	public function __get($key)
	{
		$_key = '_' . $key;
		
		if (array_key_exists($_key, get_object_vars($this)))
		{
			return $this->$_key;
		}
		
		return FALSE;
	}
	
	private function _route_uri()
	{
		// route uri
		if (defined('CLI'))
		{
			global $argv;
			
			if (isset($argv[1]))
			{
				Rti::uri()->route('/' . $argv[1]);
			}
			else
			{
				Rti::uri()->route('/');
			} 
		}
		else 
		{
			Rti::uri()->routeURL();
		}		
	}
	
	/**
	 * Run Application
	 *
	 * @access	public
	 * @return	void
	 */
	public function run()
	{
		// get controller class
		$class = Rti::uri()->routedController();
		
		// get controller method
		$method = Rti::uri()->routedMethod();
		
		// load controller
		Rti::benchmark()->start('bm_controller');
		$controller = Rti::loadController($class, 'controller');
		
		$methods = get_class_methods(get_class($controller));
		
		if ((! in_array($method, $methods)) || (substr($method, 0, 1) == '_'))
		{
			Rti::show404();
		}
		else 
		{
			// call controller method 
			$controller->$method();		
				
			Rti::benchmark()->stop('bm_controller');
		}
		
		Rti::benchmark()->stop('bm_application');
		
		Rti::profiler()->write();
	}
	
}

/* End of file RtiApplication.php */
/* Location: ./system/core/RtiApplication.php */
